<template>
  <div class="inventory-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>库存管理</h2>
      <p>管理商品库存信息，支持查询、筛选和库存调整</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.category"
            placeholder="选择商品分类"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部分类" value="" />
            <el-option label="电子产品" value="electronics" />
            <el-option label="服装" value="clothing" />
            <el-option label="食品" value="food" />
            <el-option label="日用品" value="daily" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.status"
            placeholder="库存状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="全部状态" value="" />
            <el-option label="正常" value="normal" />
            <el-option label="库存不足" value="low" />
            <el-option label="缺货" value="out" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增商品
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">{{ getCategoryName(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="currentStock" label="当前库存" width="100">
          <template #default="{ row }">
            <span :class="getStockClass(row.currentStock, row.minStock)">{{ row.currentStock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="maxStock" label="最高库存" width="100" />
        <el-table-column prop="avgCost" label="平均成本" width="100">
          <template #default="{ row }">
            ¥{{ row.avgCost.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalValue" label="库存总值" width="120">
          <template #default="{ row }">
            ¥{{ (row.currentStock * row.avgCost).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" label="最后更新" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="warning" @click="handleAdjust(row)">调整</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="productCode">
              <el-input v-model="form.productCode" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" style="width: 100%">
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装" value="clothing" />
                <el-option label="食品" value="food" />
                <el-option label="日用品" value="daily" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前库存" prop="currentStock">
              <el-input-number v-model="form.currentStock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最低库存" prop="minStock">
              <el-input-number v-model="form.minStock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高库存" prop="maxStock">
              <el-input-number v-model="form.maxStock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="平均成本" prop="avgCost">
              <el-input-number v-model="form.avgCost" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" style="width: 100%">
                <el-option label="正常" value="normal" />
                <el-option label="库存不足" value="low" />
                <el-option label="缺货" value="out" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="adjustDialogVisible"
      title="库存调整"
      width="400px"
    >
      <el-form :model="adjustForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="adjustForm.productName" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="adjustForm.currentStock" disabled />
        </el-form-item>
        <el-form-item label="调整类型">
          <el-radio-group v-model="adjustForm.type">
            <el-radio label="increase">增加</el-radio>
            <el-radio label="decrease">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量">
          <el-input-number v-model="adjustForm.quantity" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="调整原因">
          <el-input v-model="adjustForm.reason" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdjustSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const adjustDialogVisible = ref(false)
const isEdit = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  productName: '',
  category: '',
  status: ''
})

// 表单数据
const form = reactive({
  productCode: '',
  productName: '',
  category: '',
  specification: '',
  unit: '',
  currentStock: 0,
  minStock: 0,
  maxStock: 0,
  avgCost: 0,
  status: 'normal'
})

// 库存调整表单
const adjustForm = reactive({
  productName: '',
  currentStock: 0,
  type: 'increase',
  quantity: 1,
  reason: ''
})

// 表单验证规则
const rules = {
  productCode: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  currentStock: [{ required: true, message: '请输入当前库存', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }],
  maxStock: [{ required: true, message: '请输入最高库存', trigger: 'blur' }],
  avgCost: [{ required: true, message: '请输入平均成本', trigger: 'blur' }]
}

// 模拟数据
const tableData = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 14 Pro',
    category: 'electronics',
    specification: '256GB 深空黑色',
    unit: '台',
    currentStock: 50,
    minStock: 10,
    maxStock: 200,
    avgCost: 7999.00,
    status: 'normal',
    lastUpdateTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    productCode: 'P002',
    productName: '男士休闲T恤',
    category: 'clothing',
    specification: 'L码 白色',
    unit: '件',
    currentStock: 5,
    minStock: 20,
    maxStock: 500,
    avgCost: 89.00,
    status: 'low',
    lastUpdateTime: '2024-01-15 09:15:00'
  },
  {
    id: 3,
    productCode: 'P003',
    productName: '有机大米',
    category: 'food',
    specification: '5kg装',
    unit: '袋',
    currentStock: 0,
    minStock: 50,
    maxStock: 1000,
    avgCost: 45.00,
    status: 'out',
    lastUpdateTime: '2024-01-14 16:20:00'
  },
  {
    id: 4,
    productCode: 'P004',
    productName: '洗发水',
    category: 'daily',
    specification: '500ml',
    unit: '瓶',
    currentStock: 120,
    minStock: 30,
    maxStock: 300,
    avgCost: 25.00,
    status: 'normal',
    lastUpdateTime: '2024-01-15 14:45:00'
  },
  {
    id: 5,
    productCode: 'P005',
    productName: '笔记本电脑',
    category: 'electronics',
    specification: 'i7 16G 512G',
    unit: '台',
    currentStock: 25,
    minStock: 5,
    maxStock: 100,
    avgCost: 5999.00,
    status: 'normal',
    lastUpdateTime: '2024-01-15 11:20:00'
  }
])

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑商品' : '新增商品')

const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (searchForm.productName) {
    data = data.filter(item => 
      item.productName.toLowerCase().includes(searchForm.productName.toLowerCase())
    )
  }
  
  if (searchForm.category) {
    data = data.filter(item => item.category === searchForm.category)
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  totalItems.value = data.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(form, row)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品 "${row.productName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleAdjust = (row) => {
  adjustForm.productName = row.productName
  adjustForm.currentStock = row.currentStock
  adjustForm.type = 'increase'
  adjustForm.quantity = 1
  adjustForm.reason = ''
  adjustDialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === form.id)
      if (index > -1) {
        Object.assign(tableData.value[index], form, {
          lastUpdateTime: new Date().toLocaleString()
        })
        ElMessage.success('编辑成功')
      }
    } else {
      // 新增
      const newItem = {
        ...form,
        id: Date.now(),
        lastUpdateTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newItem)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
  } catch {
    ElMessage.error('请检查表单数据')
  }
}

const handleAdjustSubmit = () => {
  const item = tableData.value.find(item => item.productName === adjustForm.productName)
  if (item) {
    if (adjustForm.type === 'increase') {
      item.currentStock += adjustForm.quantity
    } else {
      item.currentStock = Math.max(0, item.currentStock - adjustForm.quantity)
    }
    
    // 更新状态
    if (item.currentStock === 0) {
      item.status = 'out'
    } else if (item.currentStock < item.minStock) {
      item.status = 'low'
    } else {
      item.status = 'normal'
    }
    
    item.lastUpdateTime = new Date().toLocaleString()
    
    ElMessage.success('库存调整成功')
    adjustDialogVisible.value = false
  }
}

const resetForm = () => {
  Object.assign(form, {
    productCode: '',
    productName: '',
    category: '',
    specification: '',
    unit: '',
    currentStock: 0,
    minStock: 0,
    maxStock: 0,
    avgCost: 0,
    status: 'normal'
  })
  formRef.value?.clearValidate()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 辅助方法
const getCategoryName = (category) => {
  const map = {
    electronics: '电子产品',
    clothing: '服装',
    food: '食品',
    daily: '日用品'
  }
  return map[category] || category
}

const getCategoryType = (category) => {
  const map = {
    electronics: 'primary',
    clothing: 'success',
    food: 'warning',
    daily: 'info'
  }
  return map[category] || ''
}

const getStatusName = (status) => {
  const map = {
    normal: '正常',
    low: '库存不足',
    out: '缺货'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    normal: 'success',
    low: 'warning',
    out: 'danger'
  }
  return map[status] || ''
}

const getStockClass = (current, min) => {
  if (current === 0) return 'stock-out'
  if (current < min) return 'stock-low'
  return 'stock-normal'
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.inventory-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.stock-normal {
  color: #67c23a;
  font-weight: bold;
}

.stock-low {
  color: #e6a23c;
  font-weight: bold;
}

.stock-out {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .inventory-management {
    padding: 10px;
  }
  
  .search-section,
  .table-section {
    padding: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>